//
//  DJCommentViewController.m
//  Adorable_Things
//
//  Created by lanou on 16/1/11.
//  Copyright © 2016年 Banana Inc. All rights reserved.
//

#import "DJCommentViewController.h"
#import "DJCommentOneTableViewCell.h"
#import "DJCommentTwoTableViewCell.h"
#import "DJCommentModel.h"
#import "DJShopViewController.h"
#import "ATMainDetailViewController.h"

#define kCommentUrl @"http://api.menghuoapp.com/v1/shop/recommend"
#define kmarkUrl @"http://api.menghuoapp.com/v1/shop/mark"
//shop_id=186&auth_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NTM5MDAyMzAsInVzZXJfaWQiOjIyODIxfQ.v0nQuw5Bet0oqeu_GmB1mvh6cSbLMzsNcjfhhBH1KdI&
#define kUnMarkUrl @"http://api.menghuoapp.com/v1/shop/unmark"


@interface DJCommentViewController () <UITableViewDataSource, UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic, strong) NSMutableArray *commentArr;
@property (nonatomic, assign) NSInteger index;
@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageSize;

@end

@implementation DJCommentViewController

- (void)loadView
{
    [super loadView];
    self.view.frame = CGRectMake(0, 50, kWidth, kHeight - 99);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor whiteColor];
   
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.pageSize = 20;
    self.category_id = @"0";
    self.commentArr = [NSMutableArray array];
    
    [self addsubView];
  //  [self setUpdata];
    
    
    self.CommentTableV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        self.page = 0;
        [self setUpdata];
    }];
    
    self.CommentTableV.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        self.page += 1;
        [self setUpdata];
    }];
    
}

- (void)setUpdata
{
    
    ATUserManager *userManager = [ATUserManager shareManager];
    NSDictionary *parDic = @{@"page_size":[NSString stringWithFormat:@"%ld",(long)self.pageSize],@"page":[NSString stringWithFormat:@"%ld", (long)self.page],@"category_id":self.category_id,@"auth_token":userManager.auth_token};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager POST:kCommentUrl parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (self.page == 0) {
            [self.commentArr removeAllObjects];
        }
        
        NSArray *dataArr = responseObject[@"data"];
        for (NSDictionary *oneDic in dataArr) {
            DJCommentModel *model = [[DJCommentModel alloc]init];
            [model setValuesForKeysWithDictionary:oneDic];
            [self.commentArr addObject:model];
        }
        [self.CommentTableV.mj_header endRefreshing];
        [self.CommentTableV.mj_footer endRefreshing];
        
        [_CommentTableV reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        NSLog(@"failure");
        
    }];
}

- (void)addsubView
{
    self.CommentHeadV.contentSize = CGSizeMake(50 * 12, 40);
    self.CommentHeadV.scrollEnabled = YES;
    self.CommentHeadV.bounces = NO;
    self.CommentHeadV.showsHorizontalScrollIndicator = NO;
    self.CommentHeadV.showsVerticalScrollIndicator = NO;
    self.CommentHeadV.delegate = self;
    for (int i = 0; i < 12; i++) {
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        button.frame = CGRectMake(50 * i, 0, 50, 40);
        [self.CommentHeadV addSubview:button];
        [button setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.tag = i + 420;
        switch (i) {
            case 0:
                [button setTitle:@"最新" forState:(UIControlStateNormal)];
                [button setTitleColor:[UIColor yellowColor] forState:(UIControlStateNormal)];
                break;
            case 1:
                [button setTitle:@"文具" forState:(UIControlStateNormal)];
                break;
            case 2:
                [button setTitle:@"家居" forState:(UIControlStateNormal)];
                break;
            case 3:
                [button setTitle:@"杂货" forState:(UIControlStateNormal)];
                break;
            case 4:
                [button setTitle:@"私物" forState:(UIControlStateNormal)];
                break;
            case 5:
                [button setTitle:@"美妆" forState:(UIControlStateNormal)];
                break;
            case 6:
                [button setTitle:@"零食" forState:(UIControlStateNormal)];
                break;
            case 7:
                [button setTitle:@"二次元" forState:(UIControlStateNormal)];
                break;
            case 8:
                [button setTitle:@"配饰" forState:(UIControlStateNormal)];
                break;
            case 9:
                [button setTitle:@"包袋" forState:(UIControlStateNormal)];
                break;
            case 10:
                [button setTitle:@"萌娃" forState:(UIControlStateNormal)];
                break;
            case 11:
                [button setTitle:@"数码" forState:(UIControlStateNormal)];
                break;
                
            default:
                break;
        }
        [button addTarget:self action:@selector(categoryButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
    }
    UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kWidth, 1)];
    lab.backgroundColor = [UIColor grayColor];
    lab.alpha = 0.3;
    [self.view addSubview:lab];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 39, kWidth, 1)];
    label.backgroundColor = [UIColor grayColor];
    label.alpha = 0.3;
    [self.view addSubview:label];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (![scrollView isKindOfClass:[UITableView class]]) {
        scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, 0);
    }
    
}

- (void)categoryButtonClick:(UIButton *)button
{
    for (int i = 0; i < 12; i++) {
        UIButton *but = [self.CommentHeadV viewWithTag:i + 420];
        [but setTitleColor:[UIColor grayColor] forState:(UIControlStateNormal)];
    }
    [button setTitleColor:[UIColor yellowColor] forState:(UIControlStateNormal)];
    self.category_id = [NSString stringWithFormat:@"%ld", button.tag - 420];
    self.CommentTableV.contentOffset = CGPointMake(0, 0);
    [self setUpdata];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.commentArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DJCommentModel *model = self.commentArr[indexPath.row];
    if (indexPath.row % 2 == 0) {
        DJCommentOneTableViewCell *Cell =[tableView dequeueReusableCellWithIdentifier:@"CommentOneCell"];
        if (Cell == nil) {
            Cell = [[[NSBundle mainBundle] loadNibNamed:@"DJCommentOneTableViewCell" owner:self options:nil] lastObject];
        }
        
        Cell.model = model;
        Cell.iconImageV.layer.cornerRadius = 25;
        Cell.iconImageV.layer.masksToBounds = YES;
        Cell.selectionStyle = UITableViewCellEditingStyleNone;
        
        [Cell.OneButton sd_setImageWithURL:[NSURL URLWithString:model.items[0][@"pic_url"]] forState:(UIControlStateNormal)];
        [Cell.OneButton addTarget:self action:@selector(DJCommentbuttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        Cell.OneButton.tag = 400 + 1000 * indexPath.row;
        [Cell.TwoButton sd_setImageWithURL:[NSURL URLWithString:model.items[1][@"pic_url"]] forState:(UIControlStateNormal)];
        [Cell.TwoButton addTarget:self action:@selector(DJCommentbuttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        Cell.TwoButton.tag = 401 + 1000 * indexPath.row;
        [Cell.ThreeButton sd_setImageWithURL:[NSURL URLWithString:model.items[2][@"pic_url"]] forState:(UIControlStateNormal)];
        [Cell.ThreeButton addTarget:self action:@selector(DJCommentbuttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        Cell.ThreeButton.tag = 402 + 1000 * indexPath.row;
        [Cell.FourButton sd_setImageWithURL:[NSURL URLWithString:model.items[3][@"pic_url"]] forState:(UIControlStateNormal)];
        [Cell.FourButton addTarget:self action:@selector(DJCommentbuttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        Cell.FourButton.tag = 403 + 1000 * indexPath.row;
        [Cell.FiveButton sd_setImageWithURL:[NSURL URLWithString:model.items[3][@"pic_url"]] forState:(UIControlStateNormal)];
        [Cell.FiveButton addTarget:self action:@selector(DJCommentbuttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        Cell.FiveButton.tag = 404 + 1000 * indexPath.row;
        
        if ([model.favorite integerValue] == 1) {
            
            [Cell.addButton setTitle:@"已关注" forState:(UIControlStateNormal)];
        }else{
             [Cell.addButton setTitle:@"+关注" forState:(UIControlStateNormal)];
        }
        [Cell.addButton addTarget:self action:@selector(addButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
         Cell.addButton.tag = 580 + indexPath.row;
        return Cell;
    }else{
        DJCommentTwoTableViewCell *Cell =[tableView dequeueReusableCellWithIdentifier:@"CommentTwoCell"];
        if (Cell == nil) {
            Cell = [[[NSBundle mainBundle] loadNibNamed:@"DJCommentTwoTableViewCell" owner:self options:nil] lastObject];
        }
        Cell.model = model;
        Cell.iconImageV.layer.cornerRadius = 25;
        Cell.iconImageV.layer.masksToBounds = YES;
        Cell.imageSrollV.contentSize = CGSizeMake(100 * model.items.count, 90);
        Cell.imageSrollV.pagingEnabled = NO;
        Cell.imageSrollV.scrollEnabled = YES;
        Cell.imageSrollV.showsHorizontalScrollIndicator = NO;
        Cell.imageSrollV.showsVerticalScrollIndicator = NO;
        for (int i = 0; i < model.items.count; i++) {
            UIButton *button = [UIButton buttonWithType:(UIButtonTypeCustom)];
            button.frame = CGRectMake(100 * i , 5, 90, 90);
            [button sd_setImageWithURL:[NSURL URLWithString:model.items[i][@"pic_url"]] forState:(UIControlStateNormal)];
            button.layer.cornerRadius = 10;
            button.layer.masksToBounds = YES;
            button.tag = 400 + i + 1000 * indexPath.row;
            [Cell.imageSrollV addSubview:button];
            [button addTarget:self action:@selector(DJCommentbuttonClick:) forControlEvents:(UIControlEventTouchUpInside)];
        }
        Cell.selectionStyle = UITableViewCellEditingStyleNone;
        if ([model.favorite integerValue] == 1) {
            [Cell.addButton setTitle:@"已关注" forState:(UIControlStateNormal)];
        }else{
            [Cell.addButton setTitle:@"+关注" forState:(UIControlStateNormal)];
        }
        [Cell.addButton addTarget:self action:@selector(addButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        Cell.addButton.tag = 580 + indexPath.row;
        
        return Cell;
    }
    
    
}

- (void)addButtonAction:(UIButton *)button
{
     DJCommentModel *model = self.commentArr[button.tag - 580];
    DJCommentTwoTableViewCell *cell = [self.CommentTableV cellForRowAtIndexPath:[NSIndexPath indexPathForRow:(button.tag - 580) inSection:0]];
    if ([model.favorite integerValue] == 1) {
        NSDictionary *parDic = @{@"shop_id":model.shop_id,@"auth_token":@"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NTM5MDAyMzAsInVzZXJfaWQiOjIyODIxfQ.v0nQuw5Bet0oqeu_GmB1mvh6cSbLMzsNcjfhhBH1KdI"};
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:kUnMarkUrl parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    
            model.favorite = [NSNumber numberWithInt:0];
            [cell.addButton setTitle:@"+关注" forState:(UIControlStateNormal)];
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
       
    }else{
        
        NSDictionary *parDic = @{@"shop_id":model.shop_id,@"auth_token":@"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE0NTM5MDAyMzAsInVzZXJfaWQiOjIyODIxfQ.v0nQuw5Bet0oqeu_GmB1mvh6cSbLMzsNcjfhhBH1KdI"};
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager POST:kmarkUrl parameters:parDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            model.favorite = [NSNumber numberWithInt:1];
            [cell.addButton setTitle:@"已关注" forState:(UIControlStateNormal)];
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];

    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DJCommentModel *model = self.commentArr[indexPath.row];
    if (model.items.count == 0) {
        return 210;
    }else{
        return 190;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   // self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    DJCommentModel *model = self.commentArr[indexPath.row];
    DJShopViewController *shopVC = [[DJShopViewController alloc]init];
    shopVC.shop_id = [NSString stringWithFormat:@"%@",model.shop_id];
    [self.navigationController pushViewController:shopVC animated:YES];
}

- (void)DJCommentbuttonClick:(UIButton *)button
{
    DJCommentModel *model = self.commentArr[button.tag / 1000];
    NSInteger index = button.tag % 1000 - 400;
    ATMainDetailViewController *mainVC = [[ATMainDetailViewController alloc]init];

    mainVC.item_id = model.items[index][@"item_id"];

    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    mainVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:mainVC animated:YES];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.pageSize = self.pageSize * (self.page + 1);
    self.page = 0;
    [self.commentArr removeAllObjects];
    [self setUpdata];
    self.page = self.pageSize / 20 - 1;
    self.pageSize = 20;
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
